package com.happy.unitconvert.common.result;

/**
 * 统一响应码定义
 */
public enum ResultCode {

  // 成功
  SUCCESS(200, "操作成功"),

  // 客户端错误 4xx
  BAD_REQUEST(400, "请求参数错误"),
  UNAUTHORIZED(401, "未授权"),
  FORBIDDEN(403, "禁止访问"),
  NOT_FOUND(404, "资源不存在"),
  METHOD_NOT_ALLOWED(405, "请求方法不支持"),
  PARAM_INVALID(422, "参数校验失败"),
  TOO_MANY_REQUESTS(429, "请求过于频繁"),

  // 服务端错误 5xx
  INTERNAL_SERVER_ERROR(500, "服务器内部错误"),
  BAD_GATEWAY(502, "网关错误"),
  SERVICE_UNAVAILABLE(503, "服务不可用"),
  GATEWAY_TIMEOUT(504, "网关超时"),

  // 业务错误码 1xxx
  BUSINESS_ERROR(1000, "业务处理失败"),
  DATA_NOT_FOUND(1001, "数据不存在"),
  DATA_ALREADY_EXISTS(1002, "数据已存在"),
  OPERATION_NOT_ALLOWED(1003, "操作不被允许"),

  // 单位转换相关错误 2xxx
  UNIT_NOT_SUPPORTED(2001, "不支持的单位类型"),
  CONVERSION_ERROR(2002, "单位转换失败"),
  INVALID_UNIT_VALUE(2003, "无效的单位数值");

  private final Integer code;
  private final String message;

  ResultCode(Integer code, String message) {
    this.code = code;
    this.message = message;
  }

  public Integer getCode() {
    return code;
  }

  public String getMessage() {
    return message;
  }

  /**
   * 根据code获取对应的ResultCode
   */
  public static ResultCode getByCode(Integer code) {
    for (ResultCode resultCode : values()) {
      if (resultCode.getCode().equals(code)) {
        return resultCode;
      }
    }
    return INTERNAL_SERVER_ERROR;
  }
}
